﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Odbc;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Win32;

namespace ComTools
{

    public partial class frmTools : Form
    {
        public frmTools()
        {
            InitializeComponent();
        }

        private void btnSplit_Click(object sender, EventArgs e)
        {
            string[] arrays = txtComposeString.Text.Split(new string[] { txtSeperator.Text.Trim() }, StringSplitOptions.RemoveEmptyEntries);
            txtComposeResult.Lines = arrays;
        }

        private void btnCompose_Click(object sender, EventArgs e)
        {
            txtComposeString.Text = String.Join(txtSeperator.Text.Trim(), txtComposeResult.Lines);
        }

        private void btnHex2Int_Click(object sender, EventArgs e)
        {
            int x = Convert.ToInt32(txtHexStr.Text.Trim().Replace(" ", "").Replace("-", ""), 16);
            txtInt.Text = x.ToString(CultureInfo.CurrentCulture);
        }

        private void btnHex2Float_Click(object sender, EventArgs e)
        {

            double y = Convert.ToDouble(txtHexStr.Text.Trim().Replace(" ", "").Replace("-", "")
                , CultureInfo.CurrentCulture);
        }

        private void btnClrVersion_Click(object sender, EventArgs e)
        {
            textBox1.AppendText(Environment.Version.ToString());
            textBox1.AppendText(Environment.NewLine);
            textBox1.AppendText(UtilityHelper.GetVersionFromRegistry());
            textBox1.AppendText(UtilityHelper.GetVersionFromAssembly());
        }

        [DllImport(dllName: "Dll1.dll",
            CharSet = CharSet.Unicode, EntryPoint = "getRandInt",
            CallingConvention = CallingConvention.StdCall)]
        private static extern int GetRandInt();

        [DllImport(dllName: "Dll1.dll",
            CharSet = CharSet.Unicode, EntryPoint = "square",
            CallingConvention = CallingConvention.StdCall)]
        private static extern int Square(int x);

        [DllImport(dllName: "Dll1.dll",
            CharSet = CharSet.Unicode, EntryPoint = "squareLong",
            CallingConvention = CallingConvention.StdCall)]
        private static extern int SquareLong(int x);

        [DllImport(dllName: "Dll1.dll",
            CharSet = CharSet.Unicode, EntryPoint = "f",
            CallingConvention = CallingConvention.StdCall)]
        private static extern int GetF(StringBuilder sb);

        [DllImport(dllName: "Dll1.dll",
            CharSet = CharSet.Unicode, EntryPoint = "getStr",
            CallingConvention = CallingConvention.StdCall)]
        private static extern string GetStr();

        [DllImport(dllName: "Dll1.dll",
            CharSet = CharSet.Unicode, EntryPoint = "getAsciis",
            CallingConvention = CallingConvention.StdCall)]
        private static extern string GetAsciis();

        [DllImport(dllName: "Dll1.dll",
            CharSet = CharSet.Unicode, EntryPoint = "getAsciiStr",
            CallingConvention = CallingConvention.StdCall)]
        private static extern StringBuilder GetAsciiStr();

        [DllImport(dllName: "Dll1.dll",
            CharSet = CharSet.Unicode, EntryPoint = "getWStr",
            CallingConvention = CallingConvention.StdCall)]
        private static extern string GetWStr();

        private void button1_Click(object sender, EventArgs e)
        {
            int q = GetRandInt();
            textBox2.AppendText(q.ToString());
            textBox2.AppendText(Environment.NewLine);

            //
            int i1 = Square(5);
            textBox2.AppendText(i1.ToString());
            //
            int y = SquareLong(6);
            textBox2.AppendText(y.ToString());
            //

            StringBuilder sb = new StringBuilder("Heleo");
            y = GetF(sb);
            textBox2.AppendText(y.ToString());

            string z = GetStr();
            textBox2.AppendText(z);
            textBox2.AppendText(Environment.NewLine);

            //IntPtr ptr = GetAsciis();
            string o1 = GetAsciis();
            //string o1 = Marshal.PtrToStringAnsi(ptr);

            //StringBuilder o1 = GetAsciis();
            textBox2.AppendText(o1);
            textBox2.AppendText(Environment.NewLine);

            string w = GetWStr();
            textBox2.AppendText(w);
            textBox2.AppendText(Environment.NewLine);

            //int x = FX(6);
            //textBox2.AppendText(x.ToString());


        }

        private String ReadRegKey()
        {
            using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\JavaSoft\Java Development Kit"))
            {
                if (registryKey == null)
                {
                    return "";
                }
                else
                {
                    string[] keys = registryKey.GetSubKeyNames();
                    RegistryKey ver = registryKey.OpenSubKey(keys[0]);
                    object path = ver.GetValue("JavaHome");
                    return path == null ? "" : path.ToString();
                }
            }
        }

        private void btnGetJDK_Click(object sender, EventArgs e)
        {
            txtJDKPath.Text = ReadRegKey();
            //
            //txtPath.Text = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Machine);
            //txtPath.AppendText(Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.User));

            txtPath.Lines = Environment.GetEnvironmentVariable("path").Split(';');
            //
            txtClassPath.Clear();
            txtClassPath.Text = Environment.GetEnvironmentVariable("CLASSPATH");
        }

        private void btnSetJDKPath_Click(object sender, EventArgs e)
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是以管理员身份启动
                string jdkpath = ReadRegKey();
                if (jdkpath.Length > 0)
                {
                    string javahome = Environment.GetEnvironmentVariable("JAVA_HOME", EnvironmentVariableTarget.Machine);
                    if (!jdkpath.Equals(javahome))
                    {
                        Environment.SetEnvironmentVariable("JAVA_HOME", jdkpath, EnvironmentVariableTarget.Machine);
                    }
                }
                //
                string classpath = Environment.GetEnvironmentVariable("CLASSPATH", EnvironmentVariableTarget.Machine);
                if (classpath == null)
                {
                    Environment.SetEnvironmentVariable("CLASSPATH",
                        @".;%JAVA_HOME%\lib;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar",
                        EnvironmentVariableTarget.Machine);
                }
            }
            else
            {
                //创建启动对象 
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件 
                startInfo.FileName = Application.ExecutablePath;
                startInfo.Arguments = "mutitance";
                //设置启动动作,确保以管理员身份运行 
                startInfo.Verb = "runas";
                //如果不是管理员，则启动UAC 
                System.Diagnostics.Process.Start(startInfo);
                //退出 
                Application.Exit();
            }
        }

        private void btnSearchIPs_Click(object sender, EventArgs e)
        {
            string[] ipaddrs = txtIPFormat.Text.Trim().Split('.');
            if (ipaddrs.Length != 4)
            {
                return;
            }
            ipaddrs[cbxIPPart.SelectedIndex] = "{0}";
            string ipformat = string.Join(".", ipaddrs);

            var thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                for (int i = 254; i > 0; i--)
                {
                    string ip = string.Format(ipformat, i);
                    bool t = UtilityHelper.PingIpOrDomainName(ip);
                    OutputLine(ip + " is " + t.ToString());
                    if (t)
                    {
                        textBox7.AppendText(ip + Environment.NewLine);
                        //break;
                    }
                }
            }));

            thread.Start();
        }

        #region 输出

        Action<string> OutputHandler = null;

        private void Output(string msg)
        {
            if (OutputHandler == null)
            {
                OutputHandler = new Action<string>((txt) =>
                {
                    txtLogs.AppendText(txt);
                });
            }
            if (txtLogs.IsHandleCreated)
            {
                txtLogs.Invoke(OutputHandler, msg);
            }
        }

        private void OutputLine(string msg)
        {
            Output(msg);
            Output(Environment.NewLine);
        }

        private void Output(string format, params object[] args)
        {
            Output(string.Format(format, args));
        }

        private void OutputLine(string format, params object[] args)
        {
            Output(format, args);
            Output(Environment.NewLine);
        }

        #endregion

        private void frmTools_Load(object sender, EventArgs e)
        {
            cbxIPPart.SelectedIndex = 3;
        }

        private void btnDetectIP_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 3;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string imgf = ofd.FileName;
            Image image = Image.FromFile(imgf);
            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            byte[] vs = new byte[ms.Length];
            //Image.Save()会改变MemoryStream的Position，需要重新Seek到Begin
            ms.Seek(0, SeekOrigin.Begin);
            ms.Read(vs, 0, vs.Length);
            string txt = Convert.ToBase64String(vs);
            txtComposeResult.Text = txt;
        }

        private void btnCompElecCS_Click(object sender, EventArgs e)
        {
            string command = textBox2.Text.Trim().Replace("-", "").Replace(" ", "");
            List<string> data = new List<string>();
            int l = command.Length;
            int sum = 0;
            for (int i = 0; i < l; i += 2)
            {
                int x = int.Parse(command.Substring(i, 2), NumberStyles.HexNumber);
                sum += x;
            }
            txtElecCS.Text = Convert.ToString(sum % 256, 16).ToUpper();
        }

        #region TabPage6 

        #region Xml文件转换

        private void btnSelFolderF_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtFolderFrom.Text = folderBrowserDialog1.SelectedPath;
        }

        private void btnSelFolderT_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog2.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtFolderTo.Text = folderBrowserDialog2.SelectedPath;
        }

        private void btnXmlConverter_Click(object sender, EventArgs e)
        {
            string fromPath = txtFolderFrom.Text.Trim();
            string toPath = txtFolderTo.Text.Trim();
            string errFile = toPath + "\\errors.txt";
            if (File.Exists(errFile))
            {
                File.Delete(errFile);
            }
            var r = Directory.EnumerateFiles(fromPath, "*.xml", SearchOption.TopDirectoryOnly);
            foreach (string fp in r)
            {
                string[] lines = File.ReadAllLines(fp, Encoding.UTF8);
                lines[2] = lines[2].Replace(".BMP</filename>", ".jpg</filename>");
                lines[3] = lines[3].Replace(".BMP</path>", ".jpg</path>");
                lines[8] = "		<width>304</width>";
                lines[9] = "		<height>304</height>";

                lines[19] = scaleRow(lines[19]);
                lines[20] = scaleRow(lines[20]);
                lines[21] = scaleRow(lines[21]);
                lines[22] = scaleRow(lines[22]);

                if (lines.Length > 30)
                {
                    lines[31] = scaleRow(lines[31]);
                    lines[32] = scaleRow(lines[32]);
                    lines[33] = scaleRow(lines[33]);
                    lines[34] = scaleRow(lines[34]);
                }
                else
                {
                    File.AppendAllText(errFile, fp + Environment.NewLine);
                }
                var tpath = toPath + "\\" + Path.GetFileName(fp);
                File.WriteAllLines(tpath, lines, Encoding.UTF8);
            }
        }

        private string scaleRow(string row)
        {
            int i1 = row.IndexOf('>');
            int i2 = row.LastIndexOf('<');
            string strv = row.Substring(i1 + 1, i2 - i1 - 1);
            int nv = int.Parse(strv) * 304 / 1280;
            string v = row.Substring(0, i1 + 1) + nv.ToString() + row.Substring(i2);
            return v;
        }

        #endregion

        private void btnGetDiffer_Click(object sender, EventArgs e)
        {
            DirectoryInfo diFrom = new DirectoryInfo(txtFolderFrom.Text.Trim());
            DirectoryInfo diTo = new DirectoryInfo(txtFolderTo.Text.Trim());
            var from = diFrom.GetFiles();
            var to = diTo.GetFiles();

            var inner = from.Intersect(to, new FileInfoCompare());
            var leftMore = from.Except(inner);
            var rightMore = to.Except(inner);

            foreach (FileInfo file in leftMore.ToList())
            {
                textBox7.AppendText(file.Name + Environment.NewLine);
            }

            foreach (FileInfo file in rightMore.ToList())
            {
                textBox8.AppendText(file.Name + Environment.NewLine);
            }
        }

        class FileInfoCompare : IEqualityComparer<FileInfo>
        {
            public bool Equals(FileInfo x, FileInfo y)
            {
                if (object.ReferenceEquals(x, y)) return true;
                return (x.Name == y.Name);
            }

            public int GetHashCode(FileInfo obj)
            {
                return obj.FullName.GetHashCode();
            }
        }

        #endregion

        #region tabPage7
        private void btnDetectDigit_Click(object sender, EventArgs e)
        {
            string url = txtBaiduUrl.Text.Trim();

            
        }

        private void btnGetToken_Click(object sender, EventArgs e)
        {
            string url = txtBaiduUrl.Text.Trim();

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("grant_type", "client_credentials");
            dic.Add("client_id", "client_credentials");
            dic.Add("client_secret", "client_credentials");
            var res = UtilityHelper.HttPost(url, dic);
            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
            
        }

        class TokenResponse
        {
            public string refresh_token { get; set; }
            public string expires_in { get; set; }
            public string scope { get; set; }
            public string session_key { get; set; }
            public string access_token { get; set; }
            public string session_secret { get; set; }
        }

        #endregion

        #region TabPage8

        private void btnRunThread_Click(object sender, EventArgs e)
        {
            string xx = "0123456789";
            OutputLineTagPage8(xx + ".Substring(0,1):" + xx.Substring(0, 1));
            OutputLineTagPage8(xx + ".Substring(1,1):" + xx.Substring(1, 1));
            OutputLineTagPage8(xx + ".Substring(2,1):" + xx.Substring(2, 1));
            OutputLineTagPage8(xx + ".Substring(3,1):" + xx.Substring(3, 1));
            OutputLineTagPage8(xx + ".Substring(4,1):" + xx.Substring(4, 1));
            
            OutputLineTagPage8(xx + ".Substring(2,1):" + xx.Substring(2, 1));
            OutputLineTagPage8(xx + ".Substring(5,3):" + xx.Substring(5, 3));

            //for (int x = 0; x < 10; x++)
            //{
            //    Thread t1 = new Thread(new ParameterizedThreadStart(RunAddPlusPlus));
            //    t1.Start(1);
            //}
        }

        private void RunAddPlusPlus(object obj)
        {
            int i = (int)obj;
            for (int x = 0; x < 1000; x++)
            {
                Thread.Sleep(50);
                i++;
            }
            OutputLineTagPage8(i.ToString());
        }

        Action<string> handler8SetText;

        private void OutputLineTagPage8(string msg)
        {
            if (handler8SetText == null)
            {
                handler8SetText = new Action<string>((txt) =>
                {
                    txtLogsTabPage8.AppendText(txt + Environment.NewLine);
                });
            }
            this.BeginInvoke(handler8SetText, msg);
        }

        #endregion

        private void btnSha256_Click(object sender, EventArgs e)
        {
            System.Security.Cryptography.SHA256 sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            var bytes = Encoding.UTF8.GetBytes(textBox18.Text.Trim()+ textBox19.Text.Trim());
            var data = sha256.ComputeHash(bytes);
            Encoding.UTF8.GetString(data);
            textBox20.Text = BitConverter.ToString(data).Replace("-", "");
        }
    }
}